package com.bootdo.program.wallpaper.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.common.utils.seq.GenerateSequenceUtil;
import com.bootdo.program.wallpaper.dao.*;
import com.bootdo.program.wallpaper.domain.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.bootdo.program.wallpaper.service.SettlemendaysBillService;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional(rollbackFor=Exception.class)
public class SettlemendaysBillService  {

	public final String DAY_ = "D";

	@Autowired
	private SettlemendaysBillDao settlemendaysBillDao;

	@Autowired
	private BalanceRecordDao balanceRecordDao;

	@Autowired
	private BzTalentDao bzTalentDao;

	@Autowired
	private BzBaseinfoDao bzBaseinfoDao;

	@Autowired
	private DistributionProfitDao distributionProfitDao;

	@Autowired
	private TzUserDao tzUserDao;

	@Autowired
	private WalletDetailsDao walletDetailsDao;

	@Autowired
	private WalletDetailsService walletDetailsService;

	@Autowired
	private DistributionProfitService distributionProfitService;
	

	public SettlemendaysBillDO get(Long id){
		return settlemendaysBillDao.get(id);
	}
	

	public List<SettlemendaysBillDO> list(Map<String, Object> map){
		return settlemendaysBillDao.list(map);
	}

	/**
	 * 查询前一天用户收益
	 * @return
	 */
	public List<SettlemendaysBillDO> selectBalanceRecord(String sTime,Integer settlemantPlatform){
		return settlemendaysBillDao.selectBalanceRecord(sTime,settlemantPlatform);
	}
	

	public int count(Map<String, Object> map){
		return settlemendaysBillDao.count(map);
	}

	public int countSett(String sTime,Integer settlemantPlatform){
		return settlemendaysBillDao.countSett(sTime,settlemantPlatform);
	}

	public int save(SettlemendaysBillDO settlemendaysBill){
		return settlemendaysBillDao.save(settlemendaysBill);
	}

	public int batchInsert(List<SettlemendaysBillDO> list){
		return settlemendaysBillDao.batchInsert(list);
	}
	

	public int update(SettlemendaysBillDO settlemendaysBill){
		return settlemendaysBillDao.update(settlemendaysBill);
	}
	

	public int remove(Long id){
		return settlemendaysBillDao.remove(id);
	}
	

	public int batchRemove(Long[] ids){
		return settlemendaysBillDao.batchRemove(ids);
	}



	@Transactional
	public int generateSettlement(BigDecimal ecpmMoney,Long sid,String sTime,Integer settlemantPlatform) throws Exception{

		List<SettlemendaysBillDO> list = settlemendaysBillDao.selectBalanceRecord(sTime,settlemantPlatform);

		if(list.size() == 0){
			return -1;
		}

		BzBaseinfoDO baseinfoDO = bzBaseinfoDao.getByPlatformType(settlemantPlatform);
		if(null == baseinfoDO){
			return -2;
		}

		//提成比例
		BigDecimal proportion = baseinfoDO.getExtensionRate().divide(new BigDecimal("100"));
		//用户提成
		BigDecimal commission = ecpmMoney.multiply(proportion);

		int i = 0;

		//结算时间
		Date date = new Date();
		DateTime settlementTime = DateUtil.parse(sTime + " " + DateUtil.format(date, "HH:mm:ss"), "yyyy-MM-dd HH:mm:ss");
		//结算单号
		String settlementNo = DateUtil.format(new Date(), "yyyyMMddHHmmss");

		for (SettlemendaysBillDO settlemendaysBillDO : list) {
			i++;
			settlemendaysBillDO.setStatus(2);
			if(1 == settlemendaysBillDO.getDtype()){
				BigDecimal amount = ecpmMoney.multiply(new BigDecimal(settlemendaysBillDO.getDownCount() + ""))
						.setScale(2,BigDecimal.ROUND_DOWN);
				settlemendaysBillDO.setAmount(amount);
			}else{
				BigDecimal amount = commission.multiply(new BigDecimal(settlemendaysBillDO.getDownCount() + ""))
						.setScale(2,BigDecimal.ROUND_DOWN);
				settlemendaysBillDO.setAmount(amount);
			}

			settlemendaysBillDO.setSettlemantPlatform(settlemantPlatform);

			settlemendaysBillDO.setSettlementTime(settlementTime);
			settlemendaysBillDO.setUpdateUser(sid);
			settlemendaysBillDO.setConfirmState(1);
			settlemendaysBillDO.setSettlementNo(DAY_ + settlementNo + i);

			//TODO 修改收益记录
			BalanceRecordDO balanceRecord = new BalanceRecordDO();
			balanceRecord.setUserId(settlemendaysBillDO.getUserid());
			balanceRecord.setStatus(2);
			balanceRecord.setUpdateTime(new Date());
			balanceRecord.setMoney(ecpmMoney);
			balanceRecord.setCreateTime(DateUtil.parse(sTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
			balanceRecord.setPlatformType(settlemantPlatform);
			settlemendaysBillDao.updateBalance(balanceRecord);
			//TODO 修改分销收益
			DistributionProfitDO profit = new DistributionProfitDO();
			profit.setCreateTime(DateUtil.parseDate(sTime));
			profit.setMoney(commission);
			profit.setPlatformType(settlemantPlatform);
			distributionProfitDao.updateByTime(profit);
		}

		return settlemendaysBillDao.batchInsert(list);
	}


	public int updateStatus(int status,String startTime,String userId,Integer settlemantPlatform) throws Exception{
		Map<String,Object> map = new HashMap<>();
		map.put("status",status);
		map.put("startTime",startTime);
		map.put("userId",userId);
		map.put("settlemantPlatform",settlemantPlatform);
		return settlemendaysBillDao.updateStatus(map);
	}


	/**
	 * 入账用户钱包
	 * @param sTime
	 * @return
	 */
	public int addWalletInfo(String sTime,Integer settlemantPlatform) throws Exception {
		List<SettlemendaysBillDO> list = settlemendaysBillDao.selectSettlementDaysInfo(sTime,settlemantPlatform);

		int size = list.size();
		if(size == 0){
			return -1;
		}

		List<SettlemendaysBillDO> doList = settlemendaysBillDao.selectSettlementDaysInfoOri(sTime,settlemantPlatform);

		//修改日结算单
		int count = settlemendaysBillDao.updateSettlementDaysInfo(sTime,settlemantPlatform);

		if(count > 0){
			//修改用户余额
			tzUserDao.batchUpdateBalanceDays(list);

			for (int j = 0; j < doList.size(); j++) {
				doList.get(j).setCreateTime(new Date());
				doList.get(j).setSettlementNo(GenerateSequenceUtil.generateSequenceNo()+""+j);
				//设置为1-收入
				doList.get(j).setDtype(1);
			}

			//新增钱包记录
			walletDetailsDao.batchSaveDay(doList);

			//修改广告收益
			updateStatus(3,sTime,null,settlemantPlatform);
			//修改分销收益
			distributionProfitService.updateStatus(3,sTime,null,settlemantPlatform);
		}else {
			throw new RuntimeException("入账失败");
		}
		return count;

	}
}
